package app1.rapidsquare.com.Utility;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import app1.rapidsquare.com.classes.AgileClass;
import app1.rapidsquare.com.classes.User;
import app1.rapidsquare.com.core.AgileSSLSocketFactore;
import app1.rapidsquare.com.database.IAgileProvider;
import app1.rapidsquare.com.core.ILoadComplete;

/**
 * Created by Hikmat on 07.08.2014.
 */
public final class Utility {

    private final static String LOG_TAG = "Agile NYC -> ";

    public final static User getUserSession(Context context) {
        if (context != null) {
            UserSessionManager userSessionManager = UserSessionManager.newInstance(context);
            return userSessionManager.getSession();
        }
        return new User();
    }

    public final static void setUserSession(Context context, User userDetails) {
        UserSessionManager userSessionManager = UserSessionManager.newInstance(context);
        userSessionManager.setSession(userDetails);
    }

    public final static void clearUserSession(Context context) {
        UserSessionManager userSessionManager = UserSessionManager.newInstance(context);
        userSessionManager.ClearSession();
    }

    private final static class UserSessionManager {
        private SharedPreferences mSharedPreferences;

        public static UserSessionManager newInstance(Context context) {
            UserSessionManager userSessionManager = new UserSessionManager(context);
            return userSessionManager;
        }

        public UserSessionManager(Context context) {
            try {
                mSharedPreferences = context.getSharedPreferences("AgileNYCUserDetailsPreferences",
                        Context.MODE_PRIVATE);
            } catch (Exception ex) {
                Log("UserSessionManager constructor", ex);
            }
        }

        public void setSession(User profileData) {
            try {
                SharedPreferences.Editor sessionEditor = mSharedPreferences.edit();

                Field[] fields = User.class.getFields();
                for (Field field : fields) {
                    String fieldType = field.getType().getName();
                    if (fieldType.equals("int")) {
                        sessionEditor.putInt(field.getName(),
                                field.getInt(profileData));

                    } else if (fieldType.equals("long")) {
                        sessionEditor.putLong(field.getName(),
                                field.getLong(profileData));

                    } else if (fieldType.equals("float")) {
                        sessionEditor.putFloat(field.getName(),
                                field.getFloat(profileData));

                    } else if (fieldType.equals("boolean")) {
                        sessionEditor.putBoolean(field.getName(),
                                field.getBoolean(profileData));

                    } else if (fieldType.equals("java.lang.String")) {
                        sessionEditor.putString(field.getName(),
                                String.valueOf(field.get(profileData)));
                    }
                }

                sessionEditor.commit();

            } catch (Exception ex) {
                Log("setSession: ", ex);
            }
        }

        public User getSession() {
            User userDetails = new User();
            try {
                Field[] fields = User.class.getFields();
                for (Field field : fields) {
                    String fieldType = field.getType().getName();

                    if (fieldType.equals("int")) {
                        field.set(userDetails,
                                mSharedPreferences.getInt(field.getName(), -1));

                    } else if (fieldType.equals("long")) {
                        field.set(userDetails,
                                mSharedPreferences.getLong(field.getName(), -1L));

                    } else if (fieldType.equals("float")) {
                        field.set(userDetails,
                                mSharedPreferences.getFloat(field.getName(), -1.0f));

                    } else if (fieldType.equals("boolean")) {
                        field.set(userDetails,
                                mSharedPreferences.getBoolean(field.getName(), false));

                    } else if (fieldType.equals("java.lang.String")) {
                        field.set(userDetails,
                                mSharedPreferences.getString(field.getName(), ""));
                    }
                }

            } catch (Exception ex) {
                Log("getSession: ", ex);
            }
            return userDetails;

        }

        public void ClearSession() {
            try {
                SharedPreferences.Editor sessionEditor = mSharedPreferences.edit();

                Field[] fields = User.class.getFields();
                for (Field field : fields) {
                    String fieldType = field.getType().getName();
                    if (fieldType.equals("int")) {
                        sessionEditor.putInt(field.getName(), -1);

                    } else if (fieldType.equals("long")) {
                        sessionEditor.putLong(field.getName(), -1L);

                    } else if (fieldType.equals("float")) {
                        sessionEditor.putFloat(field.getName(), -1.0f);

                    } else if (fieldType.equals("boolean")) {
                        sessionEditor.putBoolean(field.getName(), false);

                    } else if (fieldType.equals("java.lang.String")) {
                        sessionEditor.putString(field.getName(), "");
                    }
                    sessionEditor.commit();
                }

            } catch (Exception ex) {
                Log("ClearSession: ", ex);
            }
        }

    }

    public static <T extends AgileClass> T Deserialize(Class<T> type, String jsonObjectValue) {
        if (!Utility.isNullOrEmpty(type.getName())
                && !Utility.isNullOrEmpty(jsonObjectValue)) {
            try {
                Class<?> clazz = Class.forName(type.getName());
                Object object = clazz.newInstance();
                JSONObject jsonObject = new JSONObject(jsonObjectValue);
                Field[] fields = clazz.getFields();
                for (Field field : fields) {
                    String fieldType = field.getType().getName();
                    if (fieldType.equals("java.lang.Byte")) {
                        if (jsonObject.has(field.getName())) {
                            field.set(object,
                                    (Byte) jsonObject.get(field.getName()));
                        }

                    } else if (fieldType.equals("int")) {
                        if (jsonObject.has(field.getName())) {
                            field.set(object,
                                    jsonObject.getInt(field.getName()));
                        }

                    } else if (fieldType.equals("long")) {
                        if (jsonObject.has(field.getName())) {
                            field.set(object,
                                    jsonObject.getLong(field.getName()));
                        }

                    } else if (fieldType.equals("double")) {
                        if (jsonObject.has(field.getName())) {
                            field.set(object,
                                    jsonObject.getDouble(field.getName()));
                        }

                    } else if (fieldType.equals("float")) {
                        if (jsonObject.has(field.getName())) {
                            field.set(object,
                                    (Float) jsonObject.get(field.getName()));
                        }

                    } else if (fieldType.equals("boolean")) {
                        if (jsonObject.has(field.getName())) {
                            field.set(object,
                                    jsonObject.getBoolean(field.getName()));
                        }
                    } else if (fieldType.equals("java.lang.Boolean")) {
                        if (jsonObject.has(field.getName())) {
                            field.set(object,
                                    jsonObject.getBoolean(field.getName()));
                        }

                    } else if (fieldType.equals("java.lang.String")) {
                        if (jsonObject.has(field.getName())) {
                            field.set(object,
                                    jsonObject.getString(field.getName()));
                        }
                    } else if (fieldType.equals("java.util.Date")) {
                        if (jsonObject.has(field.getName())) {
                            field.set(object, convertJsonToDate(jsonObject
                                    .getString(field.getName())));
                        }
                    }
                }
                return (T) object;
            } catch (Exception e) {
                Utility.Log("JsonConverter Deserialize ", e);
                return null;
            }
        }

        return null;
    }

    public static <T extends AgileClass> JSONObject Serialize(T objectValue) {
        try {
            JSONObject jsonObject = new JSONObject();
            Class<?> clazz = objectValue.getClass();
            Field[] fields = clazz.getFields();

            for (Field field : fields) {
                jsonObject.accumulate(field.getName(), field.get(objectValue));
            }

            return jsonObject;

        } catch (Exception e) {
            Utility.Log("JsonConverter Serialize ", e);
            return null;
        }
    }

    private static Date convertJsonToDate(String jsonDate) {

        if (!Utility.isNullOrEmpty(jsonDate) && !jsonDate.equals("null")
                && jsonDate.length() > 0) {

            String date = jsonDate.replace("/Date(", "").replace(")/", "");
            String[] dateParts = date.split("[+-]");

            return new Date(Long.parseLong(dateParts[0]));
        }
        return new Date();
    }

    public final static void Log(String placeName, Exception ex) {
        if (ex != null)
            Log.e(LOG_TAG + placeName, ex.getMessage());
    }

    public final static void Info(String placeName, String info) {
        if (Utility.isNullOrEmpty(info))
            Log.i(LOG_TAG + placeName, info);
    }

    public final static boolean isNullOrEmpty(String s) {
        return (s == null) || (s.length() == 0);
    }

    public final static SimpleDateFormat getUTCDateFormat() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        return simpleDateFormat;
    }

    public final static Calendar getNYCDate() {
        return Calendar.getInstance(TimeZone.getTimeZone("America/New_York"));
    }

    public enum RequestMethodType {
        GET(0), POST(1);
        public int value;

        RequestMethodType(int value) {
            this.value = value;
        }
    }

    public enum SocialType {
        Email(0), Facebook(1), GooglePlus(2), LinkedIn(3), Empty(-1);
        public int value;

        SocialType(int value) {
            this.value = value;
        }
    }

    public final static void UploadImage(Context context, File file) {
        new UploadImageAsyncTask(context).execute(file);
    }

    private final static class UploadImageAsyncTask extends AsyncTask<File, Void, String> {

        private Context mContext;

        public UploadImageAsyncTask(Context context) {
            this.mContext = context;
        }

        @Override
        protected String doInBackground(File... params) {
            String line = "";
            URL url = null;
            HttpURLConnection conn = null;
            DataOutputStream dos = null;

            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = Integer.MAX_VALUE;

            try {

                url = new URL(Utility.IMAGE_UPLOAD_USER_URL + "/"
                        + getUserSession(mContext).UserToken);

                // ------------------ CLIENT REQUEST

                FileInputStream fileInputStream = new FileInputStream(params[0]);


                if (url.getProtocol().toLowerCase().equals("https")) {
                    trustAllHosts();
                    HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
                    httpsURLConnection.setHostnameVerifier(DO_NOT_VERIFY);
                    conn = httpsURLConnection;
                } else {
                    conn = (HttpURLConnection) url
                            .openConnection();
                }

                // Allow Inputs
                conn.setDoInput(true);
                // Allow Outputs
                conn.setDoOutput(true);
                // Don't use a cached copy.
                conn.setUseCaches(false);
                // Use a post method.
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Content-Type", "application/stream");
                dos = new DataOutputStream(conn.getOutputStream());

                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {
                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                }

                fileInputStream.close();
                dos.flush();
                dos.close();

                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(),
                                Utility.UTF8));
                String readLine = "";
                while ((readLine = reader.readLine()) != null) {
                    line += readLine;
                }
                reader.close();

            } catch (Exception e) {
                Utility.Log("Upload photo to the Server", e);
            }

            return line;
        }

        @Override
        protected void onPostExecute(String result) {

            try {
                if (!Utility.isNullOrEmpty(result)) {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.has("Error")) {
                        String error = jsonObject.getString("Error");
                        if (Utility.isNullOrEmpty(error)) {
                            String imageUrl = jsonObject.getString("Result");
                        }
                    }
                }
            } catch (JSONException e) {
                Utility.Log("Profile fragment convert json to object -> ", e);
            }
        }
    }

    public final static Bundle parseUrl(String url) {
        // hack to prevent MalformedURLException
        url = url.replace("fbconnect", "http");
        try {
            URL u = new URL(url);
            Bundle b = decodeUrl(u.getQuery());
            b.putAll(decodeUrl(u.getRef()));
            return b;
        } catch (MalformedURLException e) {
            return new Bundle();
        }
    }

    public final static Bundle decodeUrl(String s) {
        Bundle params = new Bundle();
        if (s != null) {
            String array[] = s.split("&");
            for (String parameter : array) {
                String v[] = parameter.split("=");

                try {
                    if (v.length == 2) {
                        params.putString(URLDecoder.decode(v[0], UTF8),
                                URLDecoder.decode(v[1], UTF8));
                    } else if (v.length == 1) {
                        params.putString(URLDecoder.decode(v[0], UTF8), "");
                    }
                } catch (UnsupportedEncodingException e) {
                    Log("Utility decode url", e);
                }
            }
        }
        return params;
    }

    public final static String ConnectServer(String url, RequestMethodType requestMethodType, StringEntity stringEntity) {
        try {

            URL mUrl = new URL(url);
            HttpURLConnection connection = null;

            if (mUrl.getProtocol().toLowerCase().equals("https")) {
                Utility.trustAllHosts();
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) mUrl.openConnection();
                httpsURLConnection.setHostnameVerifier(Utility.DO_NOT_VERIFY);
                connection = httpsURLConnection;
            } else {
                connection = (HttpURLConnection) mUrl
                        .openConnection();
            }

            connection.setRequestMethod(requestMethodType.name());
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-type", "application/json");
            connection.setRequestProperty("charset", "utf-8");
            connection.setConnectTimeout(3000);

            if (requestMethodType == Utility.RequestMethodType.POST) {
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setInstanceFollowRedirects(false);
                connection.setUseCaches(false);

                DataOutputStream wr = new DataOutputStream(
                        connection.getOutputStream());
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        stringEntity.getContent(), "utf-8"));
                StringBuilder requestStringBuilder = new StringBuilder();
                String readLine;
                while ((readLine = in.readLine()) != null) {
                    requestStringBuilder.append(readLine);
                }
                wr.writeChars(requestStringBuilder.toString());
                wr.flush();
                wr.close();
                in.close();
            }

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK)

            {
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                return response.toString();

            }

        } catch (Exception ex) {
            Utility.Log("Error is connection to the service", ex);
            return null;
        }

        return null;
    }

    public final static void AgileSyncUpdater(final IAgileProvider agileSyncClass, final ILoadComplete iLoadComplete) {
        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... voids) {
                agileSyncClass.Update();
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                if (iLoadComplete != null)
                    iLoadComplete.onLoadComplete(null);
            }
        }.execute();
    }


    // SERVICE URL
    //  public final static String SERVICE_URL = "http://81.95.226.86:84";
    //public final static String SERVICE_URL = "http://rapidsquere1.azurewebsites.net";
    //public final static String SERVICE_URL = "http://rapidsquere.cloudapp.net";
    public final static String SERVICE_URL = "https://rapidsquere.cloudapp.net";

    public final static String GOOGLE_CLOUD_SERVICE_PROJECT_NUMBER = "330300723596";
    public final static String NOTIFICATION_STATUS = "has_notification";

    public final static String AGILE_USER_PAGE_NAME = "AgileUsers.svc";
    public final static String AGILE_USER_LOGIN_METHOD_NAME = "Login";
    public final static String AGILE_USER_REGISTER_METHOD_NAME = "Register";
    public final static String AGILE_USER_CONTACTS_METHOD_NAME = "Contacts";
    public final static String AGILE_USER_DELETE_CONTACT_METHOD_NAME = "DeleteContact";
    public final static String AGILE_USER_DELETE_PHOTO_METHOD_NAME = "DeletePhoto";
    public final static String AGILE_USER_CHECK_EMAIL_METHOD_NAME = "CheckEmail";

    public final static String AGILE_USER_GET_METHOD_NAME = "GetUserDetails";
    public final static String AGILE_USER_PUT_METHOD_NAME = "SaveUserDetails";
    public final static String AGILE_USER_IMAGE_UPLOAD_METHOD_NAME = "UploadPhoto";
    public final static String AGILE_SEND_NOTIFICATION_METHOD_NAME = "SendNotification";
    public final static String AGILE_REPLY_NOTIFICATION_METHOD_NAME = "ReplyNotification";
    public final static String AGILE_CHECK_NOTIFICATION_METHOD_NAME = "CheckNotification";
    public final static String AGILE_ADD_NOTE_METHOD_NAME = "AddNote";

    public final static String AGILE_EVENT_PAGE_NAME = "AgileEvents.svc";
    public final static String AGILE_EVENT_METHOD_NAME = "Events";
    public final static String AGILE_RATING_METHOD_NAME = "Rating";
    public final static String AGILE_CHECK_IN_METHOD_NAME = "CheckIn";
    public final static String AGILE_GET_EVENT_METHOD_NAME = "Event";
    public final static String AGILE_IMAGE_HANDLER_NAME = "photo.ashx";

    //

    // SERVICE PARAMETERS


    public static String LOGIN_URL = String.format("%s/%s/%s", SERVICE_URL,
            AGILE_USER_PAGE_NAME, AGILE_USER_LOGIN_METHOD_NAME);

    public static String REGISTER_URL = String.format("%s/%s/%s", SERVICE_URL,
            AGILE_USER_PAGE_NAME, AGILE_USER_REGISTER_METHOD_NAME);

    public static String CONTACTS_URL = String.format("%s/%s/%s", SERVICE_URL,
            AGILE_USER_PAGE_NAME, AGILE_USER_CONTACTS_METHOD_NAME);

    public static String GET_USER_URL = String.format("%s/%s/%s", SERVICE_URL,
            AGILE_USER_PAGE_NAME, AGILE_USER_GET_METHOD_NAME);

    public static String SET_USER_URL = String.format("%s/%s/%s", SERVICE_URL,
            AGILE_USER_PAGE_NAME, AGILE_USER_PUT_METHOD_NAME);

    public static String IMAGE_UPLOAD_USER_URL = String.format("%s/%s/%s",
            SERVICE_URL, AGILE_USER_PAGE_NAME,
            AGILE_USER_IMAGE_UPLOAD_METHOD_NAME);

    public static String SEND_NOTIFICATION_URL = String.format("%s/%s/%s",
            SERVICE_URL, AGILE_USER_PAGE_NAME,
            AGILE_SEND_NOTIFICATION_METHOD_NAME);

    public static String REPLY_NOTIFICATION_URL = String.format("%s/%s/%s",
            SERVICE_URL, AGILE_USER_PAGE_NAME,
            AGILE_REPLY_NOTIFICATION_METHOD_NAME);

    public static String CHECK_NOTIFICATION_URL = String.format("%s/%s/%s",
            SERVICE_URL, AGILE_USER_PAGE_NAME,
            AGILE_CHECK_NOTIFICATION_METHOD_NAME);

    public static String ADD_NOTE_URL = String.format("%s/%s/%s", SERVICE_URL,
            AGILE_USER_PAGE_NAME, AGILE_ADD_NOTE_METHOD_NAME);

    public static String IMAGE_URL = String.format("%s/%s", SERVICE_URL,
            AGILE_IMAGE_HANDLER_NAME);

    public static String DELETE_CONTACT_URL = String.format("%s/%s/%s", SERVICE_URL,
            AGILE_USER_PAGE_NAME, AGILE_USER_DELETE_CONTACT_METHOD_NAME);

    public static String CHECK_EMAIL_URL = String.format("%s/%s/%s", SERVICE_URL,
            AGILE_USER_PAGE_NAME, AGILE_USER_CHECK_EMAIL_METHOD_NAME);

    public static String DELETE_PHOTO_URL = String.format("%s/%s/%s", SERVICE_URL,
            AGILE_USER_PAGE_NAME, AGILE_USER_DELETE_PHOTO_METHOD_NAME);

    //

    // EVENT


    public static String CHECK_IN_EVENT_URL = String.format("%s/%s/%s",
            SERVICE_URL, AGILE_EVENT_PAGE_NAME, AGILE_CHECK_IN_METHOD_NAME);

    public static String RATING_EVENT_URL = String.format("%s/%s/%s",
            SERVICE_URL, AGILE_EVENT_PAGE_NAME, AGILE_RATING_METHOD_NAME);

    //

    // SYNC

    public final static String AGILE_SYNC_PAGE_NAME = "AgileSync.svc";
    public final static String AGILE_CONTACTS_METHOD_NAME = "Contacts";
    public final static String AGILE_EVENTS_METHOD_NAME = "Events";
    public final static String AGILE_PARTICIPANTS_METHOD_NAME = "Participants";
    public final static String AGILE_RATINGS_METHOD_NAME = "Ratings";
    public final static String AGILE_USERS_METHOD_NAME = "Users";

    public static String CONTACTS_SYNC_URL = String.format("%s/%s/%s",
            SERVICE_URL, AGILE_SYNC_PAGE_NAME, AGILE_CONTACTS_METHOD_NAME);
    public static String EVENTS_SYNC_URL = String.format("%s/%s/%s",
            SERVICE_URL, AGILE_SYNC_PAGE_NAME, AGILE_EVENTS_METHOD_NAME);
    public static String PARTICIPANTS_SYNC_URL = String.format("%s/%s/%s",
            SERVICE_URL, AGILE_SYNC_PAGE_NAME, AGILE_PARTICIPANTS_METHOD_NAME);
    public static String RATING_SYNC_URL = String.format("%s/%s/%s",
            SERVICE_URL, AGILE_SYNC_PAGE_NAME, AGILE_RATINGS_METHOD_NAME);
    public static String USERS_SYNC_URL = String.format("%s/%s/%s",
            SERVICE_URL, AGILE_SYNC_PAGE_NAME, AGILE_USERS_METHOD_NAME);

    //

    //

    // LOCAL CONST

    public final static String UTF8 = "UTF-8";
    public final static String CODE_KEY = "code";
    public final static int INVALID_ERROR_CODE = -1;

    public final static int GOOGLE_PLUS_REQUEST_CODE = 789;
    public final static int SOCIAL_ACTIVITY_REQUEST_CODE = 11;
    public final static int LOGIN_ACTIVITY_REQUEST_CODE = 12;
    public final static int EVENT_DETAILS_ACTIVITY_REQUEST_CODE = 13;
    public final static int CONTACT_VIEW_ACTIVITY_REQUEST_CODE = 14;
    public final static int SOCIAL_NAME_ACTIVITY_REQUEST_CODE = 15;
    public final static int LINKED_IN_DATA_ACTIVITY_REQUEST_CODE = 16;
    public final static int HOW_IT_WORKS_ACTIVITY_REQUEST_CODE = 17;
    public final static int VIEW_INFO_ACTIVITY_REQUEST_CODE = 18;

    //

    // FACEBOOK

    public final static String FACEBOOK_REDIRECT_URI = "fbconnect://success";
    public final static String FACEBOOK_CANCEL_URI = "fbconnect://cancel";
    public final static String FACEBOOK_DISPLAY_TOUCH = "touch";
    public final static String FACEBOOK_ACCESS_TOKEN_URL_FORMAT = "https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=%1$s&redirect_uri="
            + FACEBOOK_REDIRECT_URI
            + "&scope=user_about_me,email,user_birthday,user_status,user_location,user_online_presence,user_hometown,user_photo_video_tags,user_photos,user_website";
    public final static String FACEBOOK_PROFILE_DATA_URL_FORMAT = "https://graph.facebook.com/me?access_token=%s";
    public final static String FACEBOOK_PROFILE_PIC_URL_FORMAT = "https://graph.facebook.com/%s/picture?request=false&type=large";

    //

    // GOOGLE PLUS

    public final static String GOOGLE_PLUS_REDIRECT_URI = "http://localhost";
    public final static String GOOGLE_PLUS_ACCESS_TOKEN_URL_FORMAT = "https://accounts.google.com/o/oauth2/auth?scope=email profile&redirect_uri="
            + GOOGLE_PLUS_REDIRECT_URI
            + "&response_type=token&client_id=%s&state=%s";

    public final static String GOOGLE_PLUS_PROFILE_DATA_URL_FORMAT = "https://www.googleapis.com/plus/v1/people/me?access_token=%s";

    private final static String G_PLUS_SCOPE = "oauth2:https://www.googleapis.com/auth/plus.me";
    private final static String USERINFO_SCOPE = "https://www.googleapis.com/auth/userinfo.profile";
    private final static String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email";
    public final static String SCOPES = G_PLUS_SCOPE + " " + USERINFO_SCOPE
            + " " + EMAIL_SCOPE;


    //

    // LINKED IN

    public final static String LINKED_IN_REDIRECT_URI = "http://www.incrementor.com";
    //public final static String LINKED_IN_REDIRECT_URI = "http://www.incrementor.ru";
    public final static String LINKED_IN_AUTHORIZATION_CODE_URL_FORMAT = "https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=%s&scope=r_fullprofile r_emailaddress r_contactinfo&state=%s&redirect_uri="
            + LINKED_IN_REDIRECT_URI;

    public final static String LINKED_IN_ACCESS_TOKEN_URL_FORMAT = "https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code=%s&client_id=%s&client_secret=%s&redirect_uri=" + LINKED_IN_REDIRECT_URI;

    public final static String LINKED_IN_ACCOUNT_URI = "https://api.linkedin.com/v1/people/~?oauth2_access_token=%s&format=json";

    public final static String LINKED_IN_ACCOUNT_PROFILE_URI = "https://api.linkedin.com/v1/people/~:(id,location:(name),phone-numbers,public-profile-url,email-address,picture-url)?oauth2_access_token=%s&format=json";

    //


    //CONST

    public final static String NOTIFICATION_BROADCASTRECEIVER_ACTION = "app1.rapidsquare.com.activity.notification.broadcastreceiver";
    public final static String LOGIN_INTENT_DATA_NAME = "app1.rapidsquare.com.activity.login.intent.data";
    public final static String SOCIAL_INTENT_DATA_NAME = "app1.rapidsquare.com.activity.social.intent.data";
    public final static String SOCIAL_TEMP_INTENT_DATA_NAME = "app1.rapidsquare.com.activity.social.temp.intent.data";
    public final static String LINKED_IN_INTENT_DATA_NAME = "app1.rapidsquare.com.activity.linkedin.intent.data";
    public final static String PROFILE_DATA_SAVEDINSTANCESTATE = "app1.rapidsquare.com.activity.profile.savedinstancestate";
    public final static String CONTACT_DATA_INTENT_DATA_NAME = "app1.rapidsquare.com.activity.contact.intent.data";
    public final static String PROFILE_DATA_IMAGE_SAVEDINSTANCESTATE = "app1.rapidsquare.com.activity.profile.image.savedinstancestate";

    public static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    public static void trustAllHosts() {
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
        }};

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            Utility.Log("SSL connection trustAllHosts", e);
        }
    }

    public static HttpClient getHttpClient() {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            SSLSocketFactory sf = new AgileSSLSocketFactore(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));

            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

            return new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            return new DefaultHttpClient();
        }
    }
}
